package cn.hfatec.utils;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * @author: panwb
 *
 * Date: 2016/4/8
 * Time: 11:24
 */
public class MailUtils {

    private static MailUtils mailUtils;

    private Properties properties;

    private Session session;

    /**
     * 获得邮件发送工具实例
     *
     * @param properties
     * @return
     */
    public static MailUtils getInstance(Properties properties) {
        if (mailUtils == null) {
            synchronized (MailUtils.class) {
                if (mailUtils == null) {
                    mailUtils = new MailUtils();
                }
            }
        }
        mailUtils.properties = properties;
        mailUtils.session = Session.getInstance(properties);
        return mailUtils;
    }

    /**
     *
     * 发送邮件
     *
     * @param to
     * @param subject
     * @param content
     * @throws MessagingException
     */
    public void send(String to, String subject, String content) throws MessagingException {

        //开启Session的debug模式，这样就可以查看到程序发送Email的运行状态
        session.setDebug(false);
        //2、通过session得到transport对象
        Transport ts = session.getTransport();
        //3、使用邮箱的用户名和密码连上邮件服务器，发送邮件时，发件人需要提交邮箱的用户名和密码给smtp服务器，用户名和密码都通过验证之后才能够正常发送邮件给收件人。
        ts.connect(properties.getProperty("mail.host"), properties.getProperty("mail.username"), properties.getProperty("mail.password"));
        //4、创建邮件
        //5、发送邮件
        MimeMessage mimeMessage = createMessage(subject, content);
        mimeMessage.setFrom(new InternetAddress(properties.getProperty("mail.account")));
        mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));

        ts.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
        ts.close();
    }

    public MimeMessage createMessage(String subject, String content) throws MessagingException {
        MimeMessage mimeMessage = new MimeMessage(session);
        mimeMessage.setSubject(subject);
        mimeMessage.setContent(content, "text/html;charset=UTF-8");
        return mimeMessage;
    }
}
